import axios from 'axios';
import router from '../router';
import {Loading,Toast } from '../plugins/index';
import qs from 'qs';

axios.defaults.timeout = 6000;
axios.defaults.baseURL ='http://sys.xin020.com/api/';

//http request 拦截器
axios.interceptors.request.use(
  config => {
    const token = globalGetToken();
    config.data = qs.stringify(config.data);
    config.headers = {
      'Content-Type':'application/x-www-form-urlencoded',
      'token':token
    };
    Loading(true);
    return config;
  },
  error => {
    Toast('请求超时！');
    Loading(false);
    return Promise.reject(err);
  }
);

//http response 拦截器
axios.interceptors.response.use(
  response => {
      let status = response.data.status;
    if(status !=0 ){
        if(status==2){
            router.replace({
                path: '/login',
                query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
            })
        }else{
          Toast(response.data.msg)
        }
    }
    Loading(false);
    return response;
  },
  error => {
    Loading(false);
    return Promise.reject(error)
  }
)

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch(url,params={}){
  return new Promise((resolve,reject) => {
    axios.get(url,{
      params:params
    })
    .then(response => {
      resolve(response.data);
    })
    .catch(err => {
      reject(err)
    })
  })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

 export function post(url,data = { }){
   return new Promise((resolve,reject) => {
     axios.post(url,data)
          .then(response => {
            resolve(response.data);
          },err => {
            reject(err)
          })
   })
 }

 /**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.patch(url,data)
         .then(response => {
           resolve(response.data);
         },err => {
           reject(err)
         })
  })
}

 /**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.put(url,data)
         .then(response => {
           resolve(response.data);
         },err => {
           reject(err)
         })
  })
}
/**
 * 获取token
 * 注意token不能为空，否则走微信验证
 */
export function globalGetToken() {
    var token = localStorage.getItem("token");
    if (token == '' || token == null || token == undefined) {
		return "appTokenNull"; 
	}
	return token;
}